package com.chinacoal.microservice.mq;

import com.alibaba.fastjson.JSONObject;
import com.chinacoal.microservice.mapper.CcmsSmartleasingExpenseManagMapper;
import com.chinacoal.microservice.mapper.CcmsSmartleasingInvoiceRecordMapper;
import com.chinacoal.microservice.pojo.BasicConfiguration;
import com.chinacoal.microservice.pojo.CcmsSmartleasingInvoiceRecord;
import com.chinacoal.microservice.pojo.Message;
import com.chinacoal.microservice.util.CodeMsg;
import com.chinacoal.microservice.util.HttpUtil;
import com.chinacoal.microservice.util.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Set;

/**
 * @Description: 延时队列，延时处理方法
 * @author: 朱亮
 * @date: 2021年03月26日 9:53
 */
@Slf4j
@Component
public class RedisMQHandle {
    @Resource
    private RedisMQ redisMQ;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private MessageSend send;

    @Autowired
    private BasicConfiguration basicConfiguration;

    @Autowired
    private CcmsSmartleasingInvoiceRecordMapper invoiceRecordMapper;

    @Autowired
    private CcmsSmartleasingExpenseManagMapper expenseManagMapper;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    /**
     * @Description: 消息队列监听器
     * @author zhuliang
     * @date 2021/3/26 14:53
     */
    @Scheduled(cron = "*/20 * * * * *")
    @Transactional
    public void monitor() throws CodeMsg {
        Set<String> set = redisUtils.rangeByScore(RedisMQ.QUEUE_NAME, 0, System.currentTimeMillis());
        if (null != set) {
            long current = System.currentTimeMillis();
            for (String id : set) {
                long  score = redisUtils.getScore(RedisMQ.QUEUE_NAME, id).longValue();
                if (current >= score) {
                    // 已超时的消息拿出来消费
                    String serialNumber = "";
                    try {
                        serialNumber = redisUtils.get(RedisMQ.MSG_POOL + id);
                        //定义查询信息体Map
                        HashMap<String, Object> serialNumberMap = new HashMap<>();

                        serialNumberMap.put("identity", basicConfiguration.getIdentity());
                        serialNumberMap.put("fpqqlsh", new String[]{serialNumber});

                        //将map转换为json字符串
                        String json = JSONObject.toJSONString(serialNumberMap) + "";

                        //调用nginx接口查询
                        String request = HttpUtil.request(basicConfiguration.getNginxUrlPC() + "/queryInvoice", json);

                        //转换格式
                        HashMap<String, Object> resultMap = JSONObject.parseObject(request, HashMap.class);
                        HashMap<String, String> list = JSONObject.parseArray(resultMap.get("list") + "", HashMap.class).get(0);
                        String cStatus = list.get("c_status");

                        //组织修改数据
                        CcmsSmartleasingInvoiceRecord smartleasingInvoiceRecord = invoiceRecordMapper.selectById(id);
                        smartleasingInvoiceRecord.setLastUpdateDate(new Date())
                                .setLastUpdatedBy(0)
                                .setMessage(list.get("c_msg"))
                                .setStatus(cStatus);

                        //判断开票状态
                        if (cStatus.equals("2")) {      //开票成功
                            //组织数据
                            smartleasingInvoiceRecord.setPdfUrl(list.get("c_url")).setImgUrl(list.get("c_jpg_url"));
                            Integer invoiceType = smartleasingInvoiceRecord.getInvoiceType();
                            if (invoiceType == 0) {
                                expenseManagMapper.updateMonthlyInvoiceStatus(new Date(), 0, "1", id);
                            } else if (invoiceType == 1){
                                expenseManagMapper.updateInvoiceStatus(new Date(), 0, "1", id);
                            } else {
                                expenseManagMapper.updateTotalInvoiceStatus(new Date(), 0, "1", id);
                            }
                            //从队列中删除信息
                            redisMQ.deMessage(RedisMQ.QUEUE_NAME, id);
                            redisMQ.deMsgPool(id);
                        } else {
                            Message message = new Message();
                            message.setId(id);
                            message.setBody(serialNumber);

                            // //从队列中删除信息(因为队列中设置了队列的过期，测试有点问题,重置几次时间后这个时间不重置了（没发现方法，如有可以修改），所以先删除在加入队列中)
                            // redisMQ.deMessage(RedisMQ.QUEUE_NAME, id);
                            // redisMQ.deMsgPool(id);

                            //重新放回队列
                            send.sendMessage(message);
                            // expenseManagMapper.updateInvoiceStatus(new Date(), 0, "2", id);
                        }

                        //写入数据库
                        invoiceRecordMapper.updateById(smartleasingInvoiceRecord);

                        log.info("消费延时任务成功：" + serialNumber + ",消费的时间：" + sdf.format(System.currentTimeMillis()));
                    } catch (Exception e) {
                        //消费异常，重新放回队列，等待异常的处理
                        Message message = new Message();
                        message.setId(id);
                        message.setBody(serialNumber);
                        //重新放回队列
                        send.sendMessage(message);

                        log.error("消费异常:" + serialNumber + ",消费的时间：" + sdf.format(System.currentTimeMillis()));
                        throw CodeMsg.OPEN_INVOICE_FAILURE;
                    }
                }
            }
        }
    }
}
